import React, { useContext, useEffect, useState } from "react";
import style from "./style.module.scss";
import {
  KeepAliveProvider,
  MyHeader,
  MypatientCieclefooter,
  NavTitle,
} from "../../components";
import { useBoolean, useRequest, useSetState } from "ahooks";
import { Swiper, List } from "react-vant";
import { getTimeFormatText } from "../../utils/formatTime";
import knowUrl1 from "../../assets/images/image/hdpi/common_disease.png";
import knowUrl2 from "../../assets/images/image/hdpi/common_drugs.png";
import health from "../../assets/images/image/xxhdpi/health_assessment.png";
import { NavLink, useNavigate } from "react-router-dom";
import {
  getBanners,
  getInformation,
  getInformationListById,
  getKnowledgeBase,
} from "../../api/home";
import VList from "../../components/vlist/vlist";
import ObserverItem from "../../components/vlist/observer-item";
import "./styles.css";
import { CacheContext } from "../../components/keepAlive/CacheContext";

// 轮播图类型
interface BannerRawState {
  imageUrl: string;
  jumpUrl: string;
  rank: number;
  title: string;
}

// 问诊咨询类型
interface KnowledgeBaseRawState {
  departmentName: string;
  id: number;
  pic: string;
  rank: number;
}

// 健康咨询标题类型
interface InfoRawState {
  id: number;
  name: string;
  sort: number;
}

// 健康咨询请求列表类型
interface InfoListRawState {
  id: number;
  plateId: number;
  releaseTime: number;
  source: string;
  thumbnail: string[];
  title: string;
}

const Index: React.FC = () => {
  const { cache, setCache } = useContext(CacheContext);
  const navigate = useNavigate();

  const { data: bannerData = [] } = useRequest<BannerRawState[], []>(
    async () => {
      if (cache.bannerData) {
        return cache.bannerData;
      }
      const resp = await getBanners();
      // 数据缓存优化
      setCache((pre) => {
        return {
          ...pre,
          bannerData: resp.result,
        };
      });
      return resp.result;
    }
  );

  // 问诊咨询请求hooks
  const { data: knowledgeBaseData = [] } = useRequest<
    KnowledgeBaseRawState[],
    []
  >(async () => {
    if (cache.knowledgeBaseData) {
      return cache.knowledgeBaseData;
    }
    const resp = await getKnowledgeBase();
    // 数据缓存优化
    setCache((pre) => {
      return {
        ...pre,
        knowledgeBaseData: resp.result,
      };
    });

    return resp.result;
  });

  // 健康咨询标题请求hooks
  const { data: infoData = [] } = useRequest<InfoRawState[], []>(async () => {
    if (cache.infoData) {
      return cache.infoData;
    }
    const resp = await getInformation();
    // 数据缓存优化
    setCache((pre) => {
      return {
        ...pre,
        infoData: resp.result,
      };
    });

    return resp.result;
  });

  // 健康咨询列表参数
  const [infoListParams, setInfoListParams] = useSetState({
    plateId: 1,
    count: 1000,
    page: 1,
  });

  // 健康咨询列表请求hooks
  const [infoListData, setInfoListData] = useState<InfoListRawState[]>([]);
  // 是否加载完毕
  const [finish, { setTrue, setFalse }] = useBoolean(false);
  // 请求合并数据
  const mergeInfoListData = async () => {
    if (cache.infoListData && cache.infoListData[infoListParams.plateId]) {
      setInfoListData(cache.infoListData[infoListParams.plateId]);
      return;
    }
    const resp = await getInformationListById(infoListParams);
    // 是否存在更多数据
    if (resp.result.length > 0) {
      // 数据二次处理
      resp.result.forEach((v) => {
        v.thumbnail = v.thumbnail.split(";");
      });
      // 请求第一页
      if (infoListParams.page === 1) {
        let data = [];
        let count = 20;
        while (--count > 0) {
          data = data.concat(resp.result);
        }
        // // 数据不合并
        // const data = new Array(1000).fill("").map((v, i) => {
        //   return resp.result[i % 20];
        // });
        setInfoListData(data);
        setCache((pre) => {
          return {
            ...pre,
            infoListData: {
              ...(pre.infoListData ? pre.infoListData : {}),
              [infoListParams.plateId]: data,
            },
            plateId: infoListParams.plateId,
          };
        });
      }
      // 下一次请求页码 + 1
      setInfoListParams({
        page: infoListParams.page + 1,
      });
    }
  };

  // 副作用 id 改变
  useEffect(() => {
    setFalse();
    mergeInfoListData();
  }, [infoListParams.plateId]);
  if (
    !bannerData.length ||
    !knowledgeBaseData.length ||
    !infoData.length ||
    !infoListData.length
  ) {
    return <></>;
  }
  return (
    <div>
      {/* // <KeepAliveProvider> */}
      <VList list={infoListData}>
        <div className={style["home"]}>
          <MyHeader showSearch={true} show></MyHeader>
          {bannerData.length > 0 && (
            <Swiper vertical={true} className={style.banner}>
              {bannerData.map((v, i) => {
                return (
                  <Swiper.Item key={i}>
                    <img src={v.imageUrl} alt="" className={style.banner} />
                  </Swiper.Item>
                );
              })}
            </Swiper>
          )}

          <NavTitle title="知识宝典"></NavTitle>
          <div className={style["know-1"]}>
            <div className={style["know-item"]}>
              <NavLink to="/home/knowledgebase?code=1">
                <p>常见病症</p>
                <div className={style["img-container"]}>
                  <img src={knowUrl1} alt="" />
                </div>
              </NavLink>
            </div>
            <div className={style["know-item"]}>
              <NavLink to="/home/knowledgebase?code=2">
                <p>常用药品</p>
                <div className={style["img-container"]}>
                  <img src={knowUrl2} alt="" />
                </div>
              </NavLink>
            </div>
          </div>
          <NavTitle title="问诊咨询"></NavTitle>
          <div className={style.know}>
            {knowledgeBaseData.map((v, i) => {
              return (
                <div
                  className={style["know-item"]}
                  key={i}
                  onClick={() =>
                    navigate(`/home/knowledgebase?code=1&left=${v.id}`)
                  }
                >
                  <img src={v.pic} alt="" className={style.img} />
                  <span>{v.departmentName}</span>
                </div>
              );
            })}
          </div>
          <NavTitle title="健康评测"></NavTitle>
          <img
            src={health}
            alt=""
            width={"100%"}
            onClick={() => navigate("/consultation/doctor/list")}
          />
          <NavTitle title="健康咨询"></NavTitle>
          <div className={style["info"]}>
            <div className={style["title"]}>
              {infoData.map((v) => {
                return (
                  <span
                    onClick={() => {
                      setInfoListParams({ plateId: v.id, page: 1 });
                    }}
                    key={v.id}
                    className={
                      v.id === infoListParams.plateId ? style["active"] : ""
                    }
                  >
                    {v.name}
                  </span>
                );
              })}
            </div>
          </div>
        </div>
        {({ index, item: v, measure }) => (
          <ObserverItem
            index={index}
            key={index}
            item={index}
            measure={measure}
          >
            {v.thumbnail.length === 1 && (
              <dl
                key={v.id}
                className={style["one"]}
                onClick={() => navigate(`/home/information/${v.id}`)}
              >
                <dt>
                  <img src={v.thumbnail[0]} alt="" />
                </dt>
                <dd>
                  <h3>{v.title}</h3>
                  <p>
                    <span>{v.source}</span>
                    <span>{getTimeFormatText(new Date(v.releaseTime))}</span>
                  </p>
                </dd>
              </dl>
            )}

            {v.thumbnail.length === 3 && (
              <dl
                key={v.id}
                className={style["three"]}
                onClick={() => navigate(`/home/information/${v.id}`)}
              >
                <dd>
                  <h3>{v.title}</h3>
                </dd>
                <dt>
                  {v.thumbnail.map((v, i) => {
                    return <img key={i} src={v}></img>;
                  })}
                </dt>
                <dd>
                  <p>
                    <span>{v.source}</span>
                    <span>{getTimeFormatText(new Date(v.releaseTime))}</span>
                  </p>
                </dd>
              </dl>
            )}

            {v.thumbnail.length === 2 && (
              <dl
                key={v.id}
                onClick={() => navigate(`/home/information/${v.id}`)}
              >
                3
              </dl>
            )}
          </ObserverItem>
        )}
      </VList>
      <MypatientCieclefooter></MypatientCieclefooter>
    </div>
  );
};

export default Index;
